from face_detect import FaceDetector, SimplePeopleObserver
from threading import Thread
import socket

HOST = ''
PORT = 50000

class TCPFaceObserver(SimplePeopleObserver):
    def __init__(self):
        SimplePeopleObserver.__init__(self)
        self.client = None
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((HOST, PORT))
        self.sock.listen(1)
	self.accept()
        
    def update(self, n):
        super(TCPFaceObserver,self).update(n) # soh para colocar print
        if self.client:
            try:
                self.client.send(('%d'%n))
            except:                
                self.accept()

    def accept(self):
	self.client = None
        x = Thread(target = self._connect)
        x.start()
    def _connect(self, *a):
        conn, addr = self.sock.accept()
        self.client = conn
        print "conectou...", addr
        self.update(self.total)
        while True:
            try:
                r = self.client.recv(1024)
                if not r:
                    break
            except:
                break
	self.accept()
    def close(self):
        print "close"
        try:
            self.sock.close()
            self.client.close()
        except:
            pass


detector = FaceDetector()
observer = TCPFaceObserver()
detector.show_window()

try:
    detector.loop(observer)
    observer.close()
except:
    observer.close()
exit(0)
